package myJs.cps

import japgolly.scalajs.react._
import japgolly.scalajs.react.vdom.all._
import myJs.Implicits._
import myJs.myPkg.DatepickerOptions
import myJs.myPkg.jquery._
import myJs.tool.Tool
import org.scalajs.dom.{Event, html}
import org.scalajs.dom.html.Input
import myJs.myPkg.Hooks._

import scala.collection.immutable.SeqMap
import scala.scalajs.js
import cats.effect._
import japgolly.scalajs.react
import japgolly.scalajs.react.util.EffectCatsEffect._

/** Created by yz on 15/9/2023
  */
object PureSelectCp {

  case class Props(
      name: String = "",
      optionMap: SeqMap[String, String],
      hasBv: Boolean = false,
      formJq: JQuery = $("#form"),
      value: String,
      onChange: String => SyncIO[Unit],
      selfClass: String = "",
      width: String = "100%",
      disabled: Boolean = false,
      extraStyle: js.UndefOr[TagMod] = js.undefined,
      colorMap: SeqMap[String, String] = SeqMap.empty
  ) {
    @inline def render: VdomElement = {
      Component(this)
    }
  }

  val Component = ScalaFnComponent[Props] { props =>
    val selectRef = react.Ref[html.Select]

    def valueChange(e: ReactEventFromInput) = {
      val v = e.target.value
      props.onChange(v)
    }

    useEffect(
      {
        SyncIO {} >> {
          if (props.optionMap.nonEmpty) {
            if (!props.optionMap.isDefinedAt(props.value)) {
              val newV = props.optionMap.keyList.head
              props.onChange(newV)
            } else SyncIO.unit
          } else props.onChange("")
        }
      },
      List(props.optionMap)
    )

    select(
      width := props.width,
      className := s"form-control ${props.selfClass}",
      props.extraStyle.whenDefined,
      name := s"${props.name}",
      value := s"${props.value}",
      onChange ==> valueChange,
      disabled := props.disabled,
      props.optionMap.toVdomArray { case (v, text) =>
        val col = props.colorMap.getOrElse(v, "#495057")
        option(
          key := s"${v}",
          fontWeight.bold,
          color := col,
          borderRadius := 0.px,
          value := s"${v}",
          s"${text}"
        )
      }
    ).withRef(selectRef)

  }

}
